<template>
  <div class="messages-container">
    <div class="header">
      <h2>消息管理</h2>
       <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        发送消息
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="消息内容">
          <el-input
            v-model="searchForm.content"
            placeholder="请输入消息内容"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="接收用户">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="阅读状态">
          <el-select
            v-model="searchForm.isRead"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="未读" :value="false" />
            <el-option label="已读" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="messages"
        stripe
        style="width: 100%"
        :row-key="(row) => row.id"
      >
      <el-table-column prop="id" label="ID"   v-if="false"/>
      <el-table-column type="index" label="序号" width="80"  />
        
        <el-table-column prop="content" label="消息内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="userName" label="接收用户" width="120" />
        <el-table-column prop="isRead" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isRead ? 'success' : 'warning'">
              {{ row.isRead ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发送时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="消息详情"
      width="600px"
      :before-close="handleDetailClose"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-item">
          <label>接收用户：</label>
          <span>{{ currentMessage.userName}}</span>
        </div>
        <div class="detail-item">
          <label>发送时间：</label>
          <span>{{ formatDate(currentMessage.createTime) }}</span>
        </div>
        <div class="detail-item">
          <label>阅读状态：</label>
          <el-tag :type="currentMessage.isRead ? 'success' : 'warning'">
            {{ currentMessage.isRead ? '已读' : '未读' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>消息内容：</label>
          <div class="content">{{ currentMessage.content }}</div>
        </div>
      </div>
    </el-dialog>

    <!-- 发送消息对话框 -->
    <el-dialog
      v-model="sendVisible"
      title="发送消息"
      width="600px"
      :before-close="handleSendClose"
    >
      <el-form
        ref="sendFormRef"
        :model="sendForm"
        :rules="sendRules"
        label-width="100px"
      >
        <el-form-item label="接收用户" prop="userId">
          <el-select
            v-model="sendForm.userId"
            placeholder="请选择接收用户"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="user.userName"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="sendForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleSendClose">取消</el-button>
        <el-button type="primary" @click="handleSendSubmit" :loading="sending">
          发送
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { Message, User } from '@/types'
import { formatDate } from '@/utils/date'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const sending = ref(false)
const messages = ref<Message[]>([])
const users = ref<User[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const detailVisible = ref(false)
const sendVisible = ref(false)
const currentMessage = ref<Message | null>(null)
const sendFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  content: '',
  userName: '',
  isRead: undefined as boolean | undefined
})

// 发送表单
const sendForm = reactive({
  userId: undefined as number | undefined,

  content: ''
})

// 发送表单验证规则
const sendRules: FormRules = {
  userId: [
    { required: true, message: '请选择接收用户', trigger: 'change' }
  ],
 
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度在 5 到 500 个字符', trigger: 'blur' }
  ]
}

// 获取消息列表
const loadMessages = async () => {
  loading.value = true
  try {
    const response = await request.get('/message/messageList', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        content: searchForm.content,
        userName: searchForm.userName,
        isRead: searchForm.isRead
      }
    })
    const dataArray = Array.isArray(response.data.data) ? response.data.data : []
    console.log(dataArray);
    
    messages.value = dataArray
    total.value = response.data.allRow || 0
    
  } catch (error) {
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const loadUsers = async () => {
  try {

    const response = await request.get('/user/selectUserName')
    console.log(response.data)
    users.value = response.data


  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadMessages()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    userName: '',
    isRead: undefined
  })
  currentPage.value = 1
  loadMessages()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadMessages()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadMessages()
}

// 查看消息详情
const handleView = (row: Message) => {
  console.log(row)
  currentMessage.value = row
  detailVisible.value = true
}

// 发送消息
const handleAdd = () => {
  sendVisible.value = true
}

// 提交发送
const handleSendSubmit = async () => {
  if (!sendFormRef.value) return
  
  try {
    await sendFormRef.value.validate()
    sending.value = true
    
    // 模拟发送操作
    await request.post(`/message/addMessage`,sendForm)
    ElMessage.success('发送成功')
    sendVisible.value = false
    Object.assign(sendForm, {
      userId: undefined,
      
      content: ''
    })
    handleSearch()
    loadMessages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发送失败')
    }
  } finally {
    sending.value = false
  }
}

// 删除消息
const handleDelete = async (row: Message) => {
  try {
    
    await ElMessageBox.confirm(
      `确定要删除该消息吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    // await new Promise(resolve => setTimeout(resolve, 500))
    await request.delete(`/message/delete/${row.id}`)
    ElMessage.success('删除成功')
    loadMessages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentMessage.value = null
}

// 关闭发送对话框
const handleSendClose = () => {
  sendVisible.value = false
  if (sendFormRef.value) {
    sendFormRef.value.resetFields()
  }
}

// 初始化
onMounted(() => {
  // 确保数据是数组
  if (!Array.isArray(messages.value)) {
    messages.value = []
  }
  if (!Array.isArray(users.value)) {
    users.value = []
  }
  loadUsers()
  loadMessages()
})
</script>

<style scoped lang="scss">


.messages-container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: $text-color;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
}

.message-detail {
  .detail-item {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;
    
    label {
      width: 100px;
      font-weight: bold;
      color: $text-color;
    }
    
    span {
      flex: 1;
      color: $text-color-regular;
    }
    
    .content {
      flex: 1;
      color: $text-color-regular;
      line-height: 1.6;
      white-space: pre-wrap;
      background-color: #f5f7fa;
      padding: 10px;
      border-radius: 4px;
    }
  }
}

</style> 